<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="exporFormVisible = true">设备管控</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">
          SN码归属导入模板
          <i class="el-icon-paperclip el-icon--right"></i>
        </el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="SN码" value="1"></el-option>
              <el-option label="归属" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="username" label="sn码归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="batch" label="批次"></el-table-column>
       <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="value" label="SN码"></el-table-column>
       <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="update_time" label="操作时间"></el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 设备远程操作 -->
    <el-dialog title="操作类型" :visible.sync="exporFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="exporForm" :rules="rules" ref="ruleForm">
        <el-form-item label="操作类型:" label-width="130px">
          <el-radio-group v-model="exporForm.snNumber" @change="operationChange">
            <el-radio label="1">多条SN</el-radio>
            <el-radio label="2">单条SN</el-radio>
            <el-radio label="3">按批次</el-radio>
            <el-radio label="4" v-if="typeBatch">按账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="操作类型:" label-width="130px">
          <el-radio-group v-model="exporForm.type">
            <el-radio label="1">重启设备</el-radio>
            <el-radio label="2">恢复出厂设置</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 导入文件start -->
        <div v-if="operationShow">
          <el-form-item label="导入文件" label-width="130px" class="snElsx">
            <div class="">
              <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="exporForm.file.name"></el-input>
              <upload-excel-component class="flex mrg-top" :before-upload="batchUpload" @submitXlsx="submitXlsx" :loading="!videoFlag">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
            </div>
          </el-form-item>
          <div v-if="batchShow">
            <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ snData.succeed}}条</el-form-item>
            <el-form-item label="相同的SN:" label-width="130px" style="margin-bottom:0"> 共{{ snData.sameData}}条
              {{ this.snData.same.length >= 1 ? `( 位于:第${this.snData.same.toString()}行 ), 只展示前10行` : ''}}
            </el-form-item>
            <el-form-item label="总条数:" label-width="130px" style="margin-bottom:0">共{{snData.all}}条</el-form-item>
          </div>
        </div>
        <!-- 导入文件end -->

        <!-- 单条SNstart -->
        <div v-if="typeSn">
          <el-form-item label="输入SN" label-width="130px" class="snElsx">
            <el-input autocomplete="off" placeholder="请输入SN码" :maxlength="30" class="sn_select" v-model="exporForm.snValue"></el-input>
          </el-form-item>
        </div>
        <!-- 单条SNend -->

        <!-- 批次或账号start -->
        <el-form-item label="选择批次:" label-width="130px" v-if="batch">
          <el-select v-model="exporForm.batch" placeholder="请选择批次" no-data-text="无数据：请在 '管控批次管理' 创立管控的批次">
            <el-option v-for="(item,index) in tathArray" :key="index" :label="item.batch" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择账号:" label-width="130px" v-if="typeAdmin">
          <el-select v-model="exporForm.username" placeholder="请选择账号">
            <el-option v-for="item in userInfo" :key="item.id" :label="item.username" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 批次或账号end -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exporFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="equipmentControl" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { resetFactory, queryResetPAD, singleSn, userResetFactory, restartOrReset } from "@/api/lock.js";
import { getBatchTwo } from "@/api/equipment.js";
import { getSelectUserId } from "@/api/dashboard.js";
import { mapState } from 'vuex'
export default {
  components: { UploadExcelComponent, dynamicTable },
  data() {
    return {
      checkboxVal: ["sn码归属", "批次", "SN码", "操作时间"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "1", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      exporFormVisible: false,
      exporForm: { type: '1', file: {}, snNumber: '1', snValue: '', batch: '', username: '' },
      rules: { pathname: [{ required: true, message: "导入文件不能为空", trigger: "blur" }] },
      gerentDisabled: true,
      batchShow: false,
      //上传后显示的数据
      snData: { same: [], sameData: 0, fail: [], succeed: '', all: '' },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, value: undefined, username: undefined },
      videoFlag: true,
      typeBatch: false,//管理员进来
      tathArray: [],//批次
      userInfo: [],//账号
      admin: 1
    }
  },
  computed: {
    operationShow() {
      return this.admin == 1 ? true : false
    },
    typeSn() {
      return this.admin == 2 ? true : false
    },
    batch() {
      return this.admin == 3 ? true : false
    },
    typeAdmin() {
      return this.admin == 4 ? true : false
    },
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getappLockList()
    //管理员进来
    if ([1, 2].includes(Number(localStorage.getItem("auth_group_id")))) {
      this.typeBatch = true
    }
    this.getBatchTwos()
    this.getSelectUserId()
  },
  methods: {
    //监听操作类型
    operationChange(val) {
      this.admin = Number(val)
    },
    //单条SN锁定或解锁
    equipmentControl() {
      switch (this.admin) {
        case 1:
          if (this.exporForm.file instanceof File) {
            if (this.batchShow) {
              this.exporFormVisible = false
            } else {
              this.$message('存在导入文件未上传，请确认是否需要上传。')
            }
          } else {
            this.exporFormVisible = false
          }
          break;
        case 2:
          let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), type: this.exporForm.type, sn: this.exporForm.snValue }
          this.getrestartOrReset(params)
          break;
        case 3:
          let batchParams = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), type: this.exporForm.type, batch: this.exporForm.batch, username: '' }
          this.getuserResetFactory(batchParams)
          break;
        case 4:
          let adminParams = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), type: this.exporForm.type, username: this.exporForm.username, batch: '' }
          this.getuserResetFactory(adminParams)
          break;
      }
    },
    //用户名或批次推送
    getuserResetFactory(params) {
      userResetFactory(params).then(res => {
        this.$message.success(res.msg)
        this.exporFormVisible = false
         this.getappLockList()
      }).catch(err => {
        this.exporFormVisible = false
      })
    },
    //单个设备重启或恢复出厂模式
    getrestartOrReset(params) {
      console.log('单个设备重启或恢复出厂模式', params)
      restartOrReset(params).then(res => {
        this.$message.success(res.msg)
        this.exporFormVisible = false
        this.getappLockList()
      }).catch(err => {
        this.exporFormVisible = false
      })
    },
    submitXlsx() {
      var fd = new FormData()
      fd.append('file', this.exporForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.exporForm.type)
      this.videoFlag = false
      resetFactory(fd).then(res => {
        this.batchShow = true
        this.snData.sameData = res.data[0].length
        this.snData.same = JSON.parse(JSON.stringify(res.data[0].splice(0, 10)))
        this.snData.succeed = res.data.excelSuccess
        this.snData.all = res.data.total
        this.$message.success(res.msg)
        this.videoFlag = true
      }).catch(err => {
        this.videoFlag = true
      })
    },
    batchUpload(file) {
      this.exporForm.file = file
    },
    getappLockList(startSize = 1, pageSize = 10, type = 1, parameter) {
      queryResetPAD(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
        console.log('--数据',res)
      }).catch(err => {
        this.browserTable = []
        this.total = 0
        console.log('--数据',err)
      })
    },
    //搜索,1:sn码,2,归属
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.value = this.searchTable
          this.getappLockList();
          break;
        case '2':
          this.listQuery.type = 3
          this.listQuery.username = this.searchTable
          this.getappLockList();
          break;
      }
    },
    //获取账号
    getSelectUserId() {
      getSelectUserId({ userId: localStorage.getItem("ID") }).then(res => {
        this.userInfo = res.data
      }).catch(err => {
        this.userInfo = []
      })
    },
    //获取批次
    getBatchTwos() {
      getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
        this.tathArray = res.data
      }).catch(err => {
        this.tathArray = []
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getappLockList();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getappLockList();
    },
    Refresh() {
      this.listQuery = {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 1,
        value: undefined,
        username: undefined
      }
      this.getappLockList()
    },
    //导入模板
    handleDownload() {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["SN码"];
        const filterVal = ["sn"];
        const list = [{ "sn": 'QNS2HIYS0003' }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: 'SN导入模板' });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    addFormclose() {
      this.$nextTick(() => {
        this.exporForm = { type: '1', file: {}, snNumber: '1', snValue: '' }
        this.admin = 1
        this.batchShow = false
        this.snData = { same: [], sameData: 0, fail: [], succeed: '', all: '' }
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
  }
}
</script>